package com.zkw.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by Administrator on 2016/4/30 0030.
 * 相当于spring中的过滤器
 *
 * 说明：需要调用ByteBuf.release()否则出现错误：【LEAK: ByteBuf.release() was not called before it's garbage-collected.】
 */
public class DiscardServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        System.out.print("server recv: ");
        while (buf.isReadable()){
            System.out.print((char) buf.readByte());
            System.out.flush();
        }
//        buf.clear();
        buf.release();

        ByteBuf wbuf = ctx.alloc().buffer().writeBytes("server发送给client".getBytes("UTF-8"));
        ctx.writeAndFlush(wbuf);
//        wbuf.clear();
        wbuf.release();

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
